package com.boarsoft.rpc.http.jetty;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.eclipse.jetty.proxy.ProxyServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.rpc.core.RpcContext;
import com.boarsoft.rpc.http.jetty.connector.ConnectorBuilder;
import com.boarsoft.rpc.http.jetty.servlet.GatewayServlet;

public class JettyGateway {
	private static final Logger log = LoggerFactory.getLogger(JettyGateway.class);

	/** 内嵌Jetty服务器 */
	protected Server server = new Server();
	
	protected ServletHandler handler = new ServletHandler();

	@Autowired
	protected RpcContext rpcContext;

	protected Set<ConnectorBuilder> connectorBuilders;

	protected ProxyServlet proxyServlet = new GatewayServlet();

	protected Map<String, String> initParameters = new HashMap<String, String>();

	@PostConstruct
	public void init() throws Exception {
		server.setHandler(handler);
		ServletHolder sh = new ServletHolder(proxyServlet);
		sh.setAsyncSupported(true);
		if (initParameters.isEmpty()) {
			initParameters.put("maxThreads", "100");
		}
		sh.setInitParameters(initParameters);
		handler.addServletWithMapping(sh, "/*");

		// FilterHolder fh = handler.addFilterWithMapping(GatewayFilter.class,
		// "/*",
		// EnumSet.of(DispatcherType.REQUEST));
		// // fh.setInitParameter("initParamKey", "InitParamValue");
		// context.addFilter(fh, "/*", EnumSet.of(DispatcherType.REQUEST));
		// context.addServlet(sh, "/*");

		for (ConnectorBuilder cb : connectorBuilders) {
			server.addConnector(cb.build(server));
		}
		server.start();
		log.info("Jetty gateway server started");
	}

	public Set<ConnectorBuilder> getConnectorBuilders() {
		return connectorBuilders;
	}

	public void setConnectorBuilders(Set<ConnectorBuilder> connectorBuilders) {
		this.connectorBuilders = connectorBuilders;
	}

	public Map<String, String> getInitParameters() {
		return initParameters;
	}

	public void setInitParameters(Map<String, String> initParameters) {
		if (initParameters == null) {
			return;
		}
		this.initParameters = initParameters;
	}

	public ProxyServlet getProxyServlet() {
		return proxyServlet;
	}

	public void setProxyServlet(ProxyServlet proxyServlet) {
		this.proxyServlet = proxyServlet;
	}

	public Server getServer() {
		return server;
	}

	public void setServer(Server server) {
		this.server = server;
	}
}
